import tpl0 from './tpl/tpl_0.tpl';
import tpl1 from './tpl/tpl_1.tpl';
import tpl2 from './tpl/tpl_2.tpl';
import tpl3 from './tpl/tpl_3.tpl';
import wrapper from './tpl/wrapper.tpl';
import  './index.scss';
import { getParentNode, tplReplace } from '../../libs/utils.js';

export default{
    name: 'NewsList',
    wrapper(top){
        return tplReplace(wrapper,{
            top
        })
    },
    tpl(otpions){
        const { data, pageNum } = otpions;
        let list = '';
        let tpl = '';

        data.map((item, index) => {
            if(!item.thumbnail_pic_s){
                tpl = tpl0;
            }else if(item.thumbnail_pic_s && !item.thumbnail_pic_s02){
                tpl = tpl1;
            }else if(item.thumbnail_pic_s02 && !item.thumbnail_pic_s03){
                tpl = tpl2;
            }else if(item.thumbnail_pic_s03){
                tpl = tpl3;
            };

            list += tplReplace(tpl,{
                pageNum,
                index,
                uniquekey: item.uniquekey,
                url: item.url,
                author: item.author_name,
                date: item.date,
                thumbnail_pic_s: item.thumbnail_pic_s,
                thumbnail_pic_s02: item.thumbnail_pic_s02,
                thumbnail_pic_s03: item.thumbnail_pic_s03,
                title: item.title
            })
            
        });

        return list;
    },
    imgShow(){
        const oImgs = document.querySelectorAll('img');

        [...oImgs].map((img) => {
            img.onload = function(){
                img.style.opacity = '1';
            }
        })
    },
    bindEvent(oList,setCurrentNews){
        oList.addEventListener('click', this._gotoDetail.bind(this,setCurrentNews));
    },
    _gotoDetail(setCurrentNews){
        let target = getParentNode(arguments[1].target);

        let options = {
            idx: target.dataset.index,
            pageNum: target.dataset.page
        }

        setCurrentNews(options);

        window.location.href =`detail.html?path=${location.pathname}`
    }
}